var gulp = require('gulp');
var gulpLoadPlugins = require('gulp-load-plugins');
var browserSync = require('browser-sync');
var $ = gulpLoadPlugins();
var reload = browserSync.reload;
var contentIncluder = require('gulp-content-includer');
gulp.task('styles', function() {
    return gulp.src('dev/scss/**/**/*')
        .pipe($.plumber())
        .pipe($.sass.sync({
            outputStyle: 'compressed',
            precision: 10,
            includePaths: ['.']
        }).on('error', $.sass.logError))
        .pipe($.autoprefixer({browsers: ['last 5 version']}))
        .pipe(gulp.dest('css'))
        .pipe(reload({stream: true}));
});
gulp.task('html', ['styles'], function() {
    return gulp.src('dev/views/pages/*.html')
        .pipe(contentIncluder({
            includerReg:/<!\-\-include\s+"([^"]+)"\-\->/g
        }))
        .pipe(gulp.dest(''));
});
gulp.task('images', function() {
    return gulp.src('dev/img/**/**/*')
        .pipe($.if($.if.isFile, $.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true,
            multipass: true}))
        // 取值范围：0-7（优化等级）,是否无损压缩jpg图片，是否隔行扫描gif进行渲染，是否多次优化svg直到完全优化
            .on('error', function (err) {
                console.log(err);
                this.end();
            })))
        .pipe(gulp.dest('img'));
});
gulp.task('fonts', function() {
    return gulp.src('dev/fonts/**/*')
        .pipe(gulp.dest('fonts'));
});
gulp.task('lib', function() {
    return gulp.src('dev/lib/**/*')
        .pipe(gulp.dest('lib'));
});
gulp.task('scripts', function () {
    return gulp.src('dev/js/**/**/*')
        .pipe($.jshint())
        .pipe($.jshint.reporter('default'))
        .pipe($.uglify())
        .pipe(gulp.dest('js'));
});

gulp.task('watch', ['html','styles','images','fonts','scripts','lib'], function() {

    gulp.watch([
        'dev/views/**/**/*.html',
        'dev/js/**/*.js',
        'dev/img/**/**/*',
        'dev/scss/**/**/*',
        'dev/fonts/**/*',
        'dev/lib/**/*'
    ]).on('change', reload);

    gulp.watch('dev/views/**/**/*.html', ['html']);
    gulp.watch('dev/lib/**/**/*', ['lib']);
    gulp.watch('dev/scss/**/**/*', ['styles']);
    gulp.watch('dev/js/**/*.js', ['scripts']);
    gulp.watch('dev/img/**/**/*', ['images']);
    gulp.watch('dev/fonts/**/*', ['fonts']);
});
